package com.software_product_construction.backend_software_product_construction.service.impl;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.software_product_construction.backend_software_product_construction.dao.LoginMapper;
import com.software_product_construction.backend_software_product_construction.service.LoginService;
import com.software_product_construction.backend_software_product_construction.util.DataAndMethodUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {
    private static Map<String,Object> phoneMap = new HashMap<>();
    private String phone = "13804972582";
    LoginMapper loginMapper;

    @Autowired
    public LoginServiceImpl(LoginMapper loginMapper) {
        this.loginMapper = loginMapper;
    }

    static{
        phoneMap.put("13804972582", new String[]{"8a216da883c633c601841f781b59108d","64d18dc345654f619e96600d90f23ef3","8a216da883c633c601841f781c6c1094"});
        phoneMap.put("13130789111", new String[]{"8aaf0708842397dd01843642df4c04e9","ddb9f220867c46f886445df4565b09bc","8aaf0708842397dd01843642e04404f0"});
    }
    @Override
    public boolean canLogin(String loginType, String username, String password) {
        boolean canLogin = false;
        if (loginType.equals("超级管理员")) {
            if (loginMapper.superLogin(username, password) > 0)
                canLogin = true;
        } else if (loginType.equals("租户")) {
            if (loginMapper.lesseeLogin(username, password) > 0)
                canLogin = true;
        } else {
            if (loginMapper.userLogin(username, password) > 0)
                canLogin = true;
        }
        return canLogin;
    }

    @Override
    public boolean codeRight(String phone, String code){
        Object o = DataAndMethodUtil.getCodeMap().get(phone);
        if(o == null){
            return false;
        }
        String initCode = ((String[]) o)[0];
        return o != null && !o.equals("") &&code.equals(initCode);
    }

    @Override
    public boolean sent(String phone){
        try {
            this.phone = phone;
            String code = this.sendAndGetVerifyCode();
            if (code != null){
                //loginMapper.addCode(code, time);
                DataAndMethodUtil.setCodeById(phone,code,String.valueOf(System.currentTimeMillis()));
                DataAndMethodUtil.startListen();
                return true;
            }
            else{
                return false;
            }
        }catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean register(String type, String username, String password, String lesseeId){
        try {
            String id = UUID.randomUUID().toString();
            if (type.equals("租户")) {
                loginMapper.lesseeRegister(id, username, password);
            } else {
                loginMapper.userRegister(id, username, password, lesseeId);
            }
            return true;
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public String sendAndGetVerifyCode(){
        //返回产生的验证码
        String code= null;
        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        String[] smsInfo = (String[]) phoneMap.get(this.phone);
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = smsInfo[0];
        String accountToken = smsInfo[1];
        //请使用管理控制台中已创建应用的APPID
        String appId = smsInfo[2];
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        //手机号码
        String to = phone;
        String templateId= "1";//使用的模板id
        //生成四位随机数
        int random=(int)(Math.random()*10000);
        code = String.valueOf(random);
        String[] datas = {code,"2"};//格式:你的验证码是{code}，请于{2}分钟内正确输入
        //HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }
        return code;
    }
}
